package com.zjw.zy

import android.app.Service
import android.content.Intent
import android.os.IBinder
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.zjw.zy.aidl.impl.AppServiceBinder
import com.zjw.zy.service.helper.TipsHelper
import com.zjw.zy.service.helper.WbSocketHelper
import com.zjw.zy.utils.AppUtils
import com.zjw.zy.utils.LogUtils
import com.zjw.zy.utils.TimeUtils
import com.zjw.zy.utils.taskpool.TaskPool

class AppService : Service(), LifecycleOwner {

    companion object {

        const val SERVICE_ACTION = "com.zjw.zy.service.APP_SERVICE"
        private const val TAG = "AppService"
    }

    private var mLifeRegister: Lifecycle? = null

    private val service = AppServiceBinder()

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        LogUtils.e(TAG, "onStartCommand")
        return START_STICKY
    }

    override fun onCreate() {
        super.onCreate()
        AppUtils.initService(this)
        //初始化时间
        TimeUtils.start(this)

        TipsHelper.init()
    }

    override fun onDestroy() {
        LogUtils.d(TAG, "onDestroy")
        AppUtils.initService(null)
        TimeUtils.stop(this)
        WbSocketHelper.getInstance().disconnectService {
            LogUtils.d(TAG, "disconnect $it")
        }
        super.onDestroy()
    }

    override fun onBind(intent: Intent): IBinder {
        return service
    }

    override fun onUnbind(intent: Intent?): Boolean {
        return super.onUnbind(intent)
    }

    override fun getLifecycle(): Lifecycle {
        if (mLifeRegister == null) {
            mLifeRegister = LifecycleRegistry(this)
        }
        return mLifeRegister!!
    }
}